<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card
      shadow="never"
      class="search-wrapper"
    >
      <el-form
        :model="queryParams"
        inline
      >
        <el-form-item label="字典类型">
          <el-select
            v-model="queryParams.dictType"
            style="width: 240px"
          >
            <el-option
              v-for="item in dictTypeList"
              :key="item.type"
              :label="item.name"
              :value="item.type"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="字典标签">
          <el-input
            v-model="queryParams.label"
            placeholder="请输入字典标签"
            clearable
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="全部状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleQuery"
          >
            搜索
          </el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button @click="goBack">返回</el-button>
          <el-button
            type="primary"
            @click="openDialog('create')"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
        />

        <el-table-column
          prop="label"
          label="标签"
        />

        <el-table-column
          prop="value"
          label="键值"
        />

        <el-table-column
          prop="sort"
          label="排序"
          width="80"
        />

        <el-table-column
          prop="status"
          label="状态"
          width="100"
        >
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="colorType"
          label="颜色类型"
        />

        <el-table-column
          prop="cssClass"
          label="CSS类"
        />

        <el-table-column
          prop="remark"
          label="备注"
        />

        <el-table-column
          label="操作"
          width="180"
        >
          <template #default="scope">
            <el-button
              size="small"
              @click="openDialog('update', scope.row.id)"
            >
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin-top: 30px"
        v-model:current-page="queryParams.pageNo"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="getList"
        @current-change="getList"
      />
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item
          label="字典类型"
          prop="dictType"
        >
          <el-input
            v-model="formData.dictType"
            :disabled="!!formData.id"
          />
        </el-form-item>

        <el-form-item
          label="数据标签"
          prop="label"
        >
          <el-input v-model="formData.label" />
        </el-form-item>

        <el-form-item
          label="数据键值"
          prop="value"
        >
          <el-input v-model="formData.value" />
        </el-form-item>

        <el-form-item
          label="显示排序"
          prop="sort"
        >
          <el-input-number
            v-model="formData.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item
          label="状态"
          prop="status"
        >
          <el-radio-group v-model="formData.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="颜色类型"
          prop="colorType"
        >
          <el-select v-model="formData.colorType">
            <el-option
              v-for="item in colorTypeOptions"
              :key="item.value"
              :label="`${item.label}(${item.value})`"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="CSS类"
          prop="cssClass"
        >
          <el-input v-model="formData.cssClass" />
        </el-form-item>

        <el-form-item
          label="备注"
          prop="remark"
        >
          <el-input
            v-model="formData.remark"
            type="textarea"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDictDataPage,
  createDictData,
  updateDictData,
  deleteDictData,
  getDictData
} from '@/api/dict/dict.data'
import { getSimpleDictTypeList } from '@/api/dict/dict.type'
import { useRoute } from 'vue-router'
import router from '@/router'

interface DictData {
  id?: number
  dictType: string
  label: string
  value: string
  sort?: number
  status: number
  colorType: string
  cssClass: string
  remark: string
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  dictType: '',
  label: '',
  status: undefined
})

const route = useRoute()

const tableData = ref<DictData[]>([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref<DictData>({
  dictType: '',
  label: '',
  value: '',
  sort: 0,
  status: 1,
  colorType: 'default',
  cssClass: '',
  remark: ''
})
const formRef = ref()
const dictTypeList = ref<any[]>([])
const statusOptions = [
  { value: 0, label: '启用' },
  { value: 1, label: '停用' }
]
const colorTypeOptions = [
  { value: 'default', label: '默认' },
  { value: 'primary', label: '主要' },
  { value: 'success', label: '成功' },
  { value: 'info', label: '信息' },
  { value: 'warning', label: '警告' },
  { value: 'danger', label: '危险' }
]

const formRules = {
  dictType: [{ required: true, message: '请选择字典类型', trigger: 'blur' }],
  label: [{ required: true, message: '请输入数据标签', trigger: 'blur' }],
  value: [{ required: true, message: '请输入数据键值', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getDictDataPage(queryParams)
    tableData.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNo = 1
  queryParams.dictType = ''
  queryParams.label = ''
  queryParams.status = undefined
  getList()
}

// 打开弹窗
const openDialog = async (type: string, id?: number) => {
  dialogTitle.value = type === 'create' ? '新增字典数据' : '修改字典数据'
  dialogVisible.value = true

  if (type === 'update' && id) {
    const res = await getDictData(id)
    formData.value = res
  } else {
    formData.value = {
      dictType: queryParams.dictType,
      label: '',
      value: '',
      sort: 0,
      status: 1,
      colorType: 'default',
      cssClass: '',
      remark: ''
    }
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()

  if (formData.value.id) {
    await updateDictData(formData.value)
    ElMessage.success('修改成功')
  } else {
    await createDictData(formData.value)
    ElMessage.success('新增成功')
  }

  dialogVisible.value = false
  getList()
}

// 删除
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm('确认删除该字典数据？')
  await deleteDictData(id)
  ElMessage.success('删除成功')
  getList()
}

const goBack = () => {
  router.go(-1)
}

// 初始化加载
onMounted(async () => {
  queryParams.dictType = route.query.type as string
  await getList()
  dictTypeList.value = await getSimpleDictTypeList()
})
</script>

<style scoped>
.search-wrapper {
  margin-bottom: 20px;
}
</style>
